package com.may.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program: com.may.netty
 * @description: 使用一个 bytebuffer 读写文本
 * @author: Bobby.Ma
 * @create: 2020-08-02 15:15
 **/
public class NIOFileChannel03 {
    /**
     * logger
     */
    private static final Logger log = LoggerFactory.getLogger(NIOFileChannel03.class);

    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\19167\\Documents\\read.txt");
        FileChannel inChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\19167\\Documents\\write.txt");
        FileChannel outChannel = fileOutputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(512);
        int read;
        while ((read = inChannel.read(buffer)) != -1) {
            log.info("read：{}", read);
            buffer.flip();
            outChannel.write(buffer);
            //重置标志位，但不会清空数据
            buffer.clear();
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}
